/**
 * 
 */
package com.vector.ding.safe.shiro;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.vector.ding.dao.mybatis.model.User;
import com.vector.ding.safe.IUser;
import com.vector.ding.safe.SecurityService;
import com.vector.ding.safe.impl.DefaultUser;

/**
 * @author vector
 *
 */
public class DefaultAuthorizingRealm extends AuthorizingRealm {

	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// TODO 授权（访问控制）
		System.out.println("shiro auth");
		return null;
	}

	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		// 登录认证
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String userName = upToken.getUsername();
		String password = String.valueOf(upToken.getPassword());
		String pwMd5 = new Md5Hash(password).toString();

		if (!SecurityService.hasUser(userName, pwMd5)) {
			throw new UnknownAccountException(String.format(
					"no account for user[username=%s, passwors=%s]!", userName, password));
		}
		
		User userBean = SecurityService.getUser(userName, pwMd5);
		if (null == userBean) {
			throw new AccountException(String.format(
					"get user[%s] object form database error!", userName));
		}
		
		IUser user = new DefaultUser(userBean);
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
				user, password.toCharArray(), getName());
		return info;
	}

}
